﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Caifu
{
	/// <summary>
	/// 绑定实用类
	/// </summary>
	public class BindUtil
	{
		/// <summary>
		/// 将对象属性的值赋给对应页面控件的值。
		/// </summary>
		/// <param name="entity">实例对象</param>
		/// <param name="page">Page对象</param>
		/// <param name="ctrlIdPrefix">控件ID前缀</param>
		public static void Bind2Page(object entity, Page page, string ctrlIdPrefix)
		{
			Dictionary<string, object> kvdict = GetPropertyNameAndValues(entity);
			var ctrls = page.Form.Controls;

			foreach (var item in ctrls)
			{
				var ctrl = item as Control;
				if (ctrl != null && ctrl.ID != null)
				{
					var ctrlIdNoPrefix = ctrlIdPrefix;
					if (!String.IsNullOrEmpty(ctrlIdPrefix))
					{
						ctrlIdNoPrefix = ctrl.ID.Remove(0, ctrlIdPrefix.Length);
					}

					if (ctrlIdNoPrefix == "") continue;
					if (kvdict.ContainsKey(ctrlIdNoPrefix))
					{// 设置控件值
						var value = kvdict[ctrlIdNoPrefix];
						if (value != null)
						{
							SetControlValue(ctrl, value);
						}
					}
				}
			}
		}

		/// <summary>
		/// 将字典中的键值与下拉框绑定。
		/// </summary>
		/// <param name="dict">字典</param>
		/// <param name="ddl">下拉框对象</param>
		public static void Bind2DropDownList(Dictionary<object, object> dict, DropDownList ddl)
		{
			ddl.Items.Clear();
			ddl.DataSource = dict.Select(kv => new { Value = kv.Key, Text = kv.Value }).ToList();
			ddl.DataValueField = "Value";
			ddl.DataTextField = "Text";
			ddl.DataBind();
		}

		/// <summary>
		/// 获取实例对象公开可读属性的名称与值，并形成一个字典返回。
		/// </summary>
		/// <param name="entity">实例对象</param>
		/// <returns>以属性名称为键，属性值为值的字典。</returns>
		static Dictionary<string, object> GetPropertyNameAndValues(object entity)
		{
			var properties = entity.GetType().GetProperties();
			var props = new Dictionary<string, object>();
			foreach (var property in properties)
			{
				props.Add(property.Name, property.GetValue(entity, null));
			}
			return props;
		}

		/// <summary>
		/// 设置控件值。
		/// </summary>
		/// <param name="ctrl">控件实例</param>
		/// <param name="value">值</param>
		static void SetControlValue(Control ctrl, object value)
		{
			if (ctrl is TextBox)
			{
				var textBox = (TextBox)ctrl;
				textBox.Text = value.ToString();
			}
			else if (ctrl is DropDownList)
			{
				var dropDownList = (DropDownList)ctrl;
				dropDownList.SelectedValue = value.ToString();
			}
			else if (ctrl is CheckBox)
			{
				var checkBox = (CheckBox)ctrl;
				checkBox.Checked = (Boolean)value;
			}
		}
	}
}
